package ece1779.ec2;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;


public class FileGallery extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException {
        try {

        	// Create a factory for disk-based file items
        	FileItemFactory factory = new DiskFileItemFactory();

        	// Create a new file upload handler
        	ServletFileUpload upload = new ServletFileUpload(factory);

        	// Parse the request
        	List /* FileItem */ items = upload.parseRequest(request);
        	
        	
        	// User ID
        	FileItem item1 = (FileItem)items.get(0);
        	
        	String name = item1.getFieldName();
        	String userID = item1.getString();
        	
        	
        	
        	response.setContentType("text/html");
        	PrintWriter out = response.getWriter();
        	
            out.write("<html><head><title>Sample Image Upload</title></head>");
            out.write("<body>");
            
            printUserImages(userID, out);

            out.write("</body></html>");
             
	}
	catch (Exception ex) {
	    throw new ServletException (ex);
	}
	
    }
    public void printUserImages(String userID, PrintWriter out) {
    	Connection con = null;
    	try{ 
            // In real life, you should get these values from a shopping cart
            int userid = userID.hashCode();
            
		    // Get DB connection from pool
		    DataSource dbcp = (DataSource)this.getServletContext().getAttribute("dbpool");
		    con = dbcp.getConnection();
	
		    // Execute SQL query
		    Statement stmt = con.createStatement();
            String    sql = "SELECT * FROM group1.images WHERE userId =" + userid;
            ResultSet rs =  stmt.executeQuery(sql);
            
            if (rs != null){
            	while (rs.next()){
            		int imageId = rs.getInt("imageId");
            		String imgURL = rs.getString("key1");
            		out.write("<a href=PreImage?imageid=" + imageId + "><img src='http://s3.amazonaws.com/s3ece1779/" + imgURL + "' /></a><br>");
            	}
            }
            
        }
    	catch(Exception ex) {
              getServletContext().log(ex.getMessage());  
    	}    	
    	finally {
    		try {
    		con.close();
    		}
    		catch (Exception e) {
                getServletContext().log(e.getMessage());  
    		}
    	}
 
    }   
}